﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Web.Mvc
{
    public static class ModelStateExtension
    {
        /// <summary>
        /// 获取所有错误信息集合
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public static List<string> GetAllErrorMessages(this ModelStateDictionary state)
        {
            List<string> result = new List<string>();
            foreach (var item in state.Values)
            {
                if (item.Errors.Count > 0)
                {
                    for (int i = item.Errors.Count - 1; i >= 0; i--)
                    {
                        result.Add(item.Errors[i].ErrorMessage);
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 检测是否验证通过，没通过会将错误信息按照html换行格式抛出异常
        /// </summary>
        /// <param name="state"></param>
        public static string CheckHtmlErrorMsg(this ModelStateDictionary state)
        {
            var result = string.Empty;
            if (!state.IsValid)
            {
                List<string> msgs = state.GetAllErrorMessages();
                result = string.Join("<br/>", msgs.ToArray());
            }
            return result;
        }
    }
}
